﻿using Caliburn.Micro;
using ExcelLibrary.BinaryFileFormat;
using ExcelLibrary.CompoundDocumentFormat;
using ExcelLibrary.SpreadSheet;
using QiHe.CodeLib;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;

namespace csExcel.views
{
    public class ImportExcelViewModel : PropertyChangedBase, IDisposable
    {
        private DataView _dg;
        public DataView dg
        {
            get { return _dg; }
            set
            {
                _dg = value;
                NotifyOfPropertyChange(() => dg);
            }
        }

        public List<string> ItemsSheet { get; private set; }
        int _SelectedItemsSheetIndex;
        public int SelectedItemsSheetIndex
        {
            get
            {
                return _SelectedItemsSheetIndex;
            }
            set
            {
                _SelectedItemsSheetIndex = value;
                NotifyOfPropertyChange(() => SelectedItemsSheetIndex);
            }
        }

        private string _filePath;
        private CompoundDocument ExcelDoc;
        Workbook _book;
        public ImportExcelViewModel(string filePath)
        {
            _filePath = filePath;
            ExcelDoc = CompoundDocument.Open(_filePath);

            byte[] bookdata = ExcelDoc.GetStreamData("Workbook");
            if (bookdata == null) return;
            _book = WorkbookDecoder.Decode(new MemoryStream(bookdata));

            ItemsSheet = new List<string>();
            foreach (Worksheet sheet in _book.Worksheets)
            {
                ItemsSheet.Add(sheet.Name);
            }
            SelectedItemsSheetIndex = 0;
        }

        public void SelectedItemChanged(int index)
        {
            Worksheet sheet = _book.Worksheets[index];
            Dictionary<int, Row> dic = sheet.Cells.Rows;

            DataTable dt = new DataTable();

            
            for (int i = 0; i <= sheet.Cells.LastColIndex; i++)
                dt.Columns.Add(new DataColumn());
            for (int i = 0; i <= sheet.Cells.LastRowIndex; i++)
                dt.Rows.Add();

            foreach (Pair<Pair<int, int>, Cell> cell in sheet.Cells)
            {
                dt.Rows[cell.Left.Left][cell.Left.Right] = cell.Right.Value.ToString();
            }
            dg = dt.DefaultView;            
        }

        ~ImportExcelViewModel()
        {
            Dispose(false);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (ExcelDoc != null)
                ExcelDoc.Close();
            if (disposing)
                GC.SuppressFinalize(this);
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}
